# -*- coding: utf-8 -*-
import requests
import os
from datetime import datetime

juhe_url = 'http://v.juhe.cn/'
app_key = '884fb622c0569f147600d2f68a3a4be4'


class Calendar:

    def calendar_day(self, date=datetime.now()):
        url = juhe_url + 'calendar/day'
        date = datetime.strptime(date, '%Y-%m-%d')
        year = date.strftime('%Y')
        month = date.strftime('%m')
        day = date.strftime('%d')
        params = {
            'date': '{}-{}-{}'.format(year, month, day),
            'key': app_key
        }
        response = requests.get(url=url, params=params)
        if response.status_code == 200:  # 请求成功
            return response.json()  # 返回结果
        else:
            return None  # 请求失败

    def is_holiday(self, date=datetime.now()):  # 调用第三方接口
        info = self.calendar_day(date)  # 获得数据
        if info is not None and info['reason'] == 'Success':  # 验证数据正确
            result = info['result']
            data = result['data']
            if 'holiday' in data:
                return "今天是节假日的%s" % data['holiday']  # 有holiday时，表示时假日
            else:
                return '今天是非节假日'
        return '数据查询异常'

    def save_data(self, date=datetime.now()):
        data = self.is_holiday(date)
        today = '{}-{}-{} {}:{}:{}'.format(datetime.now().year, datetime.now().month, datetime.now().day,
                                           datetime.now().hour, datetime.now().minute, datetime.now().second)
        f = open('calendar_day.txt', 'a')

        f.write('{} 进行了对日期的查询,  查询的结果：{}  {} \n'.format(today, date, data))
        f.close()
        self.read_data('calendar_day.txt')

    def read_data(self, txt):
        if os.path.exists(txt):
            f = open(txt, 'r')
            f_content = f.read()
            print('由于考虑接口请求次数，所有将每次的请求保存为txt，方便下次查阅，下面是进行请求后保存的数据：')
            print(f_content)
            f.close()
        else:
            pass


if __name__ == '__main__':
    cad = Calendar()
    cad.save_data('2019-10-1')
